package com.yunxiao.cloud.web.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: DataSourceConfiguration
 * @author: yunxiao
 * @date: 2020/1/19 15:28
 * @version: V1.0
 **/
@Configuration
public class DataSourceConfig {

    @Bean(name = "ds1")
    @ConfigurationProperties(prefix = "spring.datasource.druid.ds1")
    public DataSource dataSource1() {
        return new DruidDataSource();
    }

    @Bean(name = "ds3")
    @ConfigurationProperties(prefix = "spring.datasource.druid.ds3")
    public DataSource dataSource3() {
        return new DruidDataSource();
    }

    @Bean(name = "ds2")
    @ConfigurationProperties(prefix = "spring.datasource.druid.ds2")
    public DataSource dataSource2() {
        return new DruidDataSource();
    }

    @Bean("whhDataSource")
    @Primary
    public DataSource whhDataSource() {
        WhhDataSource dataSource = new WhhDataSource();
        dataSource.setDefaultTargetDataSource(dataSource1());
        Map<Object, Object> dataSourceMap = new HashMap<>(16);
        dataSourceMap.put(DataSourceEnum.TEST1.getName(), dataSource1());
        dataSourceMap.put(DataSourceEnum.TEST2.getName(), dataSource2());
        dataSourceMap.put(DataSourceEnum.TEST3.getName(), dataSource3());
        dataSource.setTargetDataSources(dataSourceMap);
        return dataSource;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(whhDataSource());
    }
}
